<?php
namespace app\shop\library;
use cubox\Cubox;
use app\shop\library\ApiController;
use app\shop\library\coupon\Coupon;
use app\shop\library\order\Stock;

class Goods{

    public static function get($id){
        $shop = Cubox::app('shop');
        $cachename  = ApiController::cacheName('goods',$id);
        $cache = $shop->cache();
        
        if ($cache->exists($cachename)){

            $str = $cache->get($cachename)??'[]';
            if ($str == 'off'){
                return false;
            }else{
                $data = json_decode($str??'[]',true);
            }
        }else{
            $goods = $shop->model('Goods');
            $data  =  $goods->getId($id);
            if (!$data) return false;

            if ($data['status']=='off'){
                $cache->set($cachename,'off');
                return false;
            }
            
            if ($data['sku_param']){
                $data['sku_param'] = json_decode($data['sku_param'],true);
                //获取规格
                $goodsSku = $shop->model('GoodsSku');
                $sku = $goodsSku->field('sku_id,indexs,name,title,price,weight,stock,barcode,default_value')->order('indexs','asc')->where('goods_id',$id)->getData();
                $data['sku'] = $sku;
            }
            $data['coupon'] =  Coupon::getGoodsCoupons($id,$data['cate_id']);
            $cache->set($cachename,json_encode($data));
            $cache->expire($cachename,3600);
        }
        
        if (isset($data['sku'])){
            foreach ($data['sku'] as $key => $skuItem){
                $data['sku'][$key]['stock'] = Stock::getGoodsSkuNum($id,$skuItem['sku_id']);
                if ($skuItem['default_value']){
                    $data['stock'] = $data['sku'][$key]['stock'];
                }
            }
        }else{
            $data['stock'] = Stock::getGoodsNum($id);
        }

        return $data;
    }
}